package com.hk.dyeyuesystem;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.hk.dyeyuesystem.db.DBOpenHelper;
import com.hk.dyeyuesystem.model.AccountBookRelation;
import com.hk.dyeyuesystem.model.Book;
import com.hk.dyeyuesystem.model.vo.AccountBookRelationVO;
import com.hk.dyeyuesystem.util.DateUtil;
import com.hk.dyeyuesystem.util.ToastUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图书挂失页面相关操作
 */
public class LossBookActivity extends AppCompatActivity {

    private static String REPOSR_LOSS = "挂失中";

    //    Initialize Toast
    private Toast toast;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

    //    Initialize ListView
    private ListView queryLossListView;

//    登录ID
    private String loginId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loss_book);
//        数据库连接实例化
        dbOpenHelper = new DBOpenHelper(LossBookActivity.this,"db_book_system",null,1);
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        获取传递的登录账号ID
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        loginId = bundle.getString("loginId");

//        获取ListView控制权
        queryLossListView = findViewById(R.id.query_loss_book_list_view);
//        添加长按点击弹出选项框菜单
        queryLossListView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("选择操作！");
                menu.add(0,0,0,"挂失图书");
            }
        });

        /**
         * 查询借阅记录并进行渲染
         */
        findByLoginId(loginId,readableDatabase);

    }

    /**
     * 开始查询该账号借阅记录,并进行渲染
     * 1、通过登录账号ID查询借阅记录，并去除已挂失的借阅书籍(与挂失记录进行对比)
     * 2、查询书籍详情并进行封装
     * @param loginId 登录账号ID
     * @param readableDatabase 数据库操作API
     */
    private void findByLoginId(String loginId, SQLiteDatabase readableDatabase) {
//        当前日期
        String dateString = DateUtil.dateString(new Date(), "yyyy-MM-dd");
        String where = "AID = ?";
//         通过账号ID查询借阅记录
        List<AccountBookRelation> accountBookRelationList = new ArrayList<>();
        Cursor cursor = readableDatabase.query("ACCOUNT_BOOK_RELATION", null, where, new String[]{loginId}, null, null, null);
        /**
         * 判断是否具有借阅记录
         *  有，进行封装
         *  没有，则进行提示
         */
        while (cursor.moveToNext()) {
            Integer aid = null;
            Integer bid = null;
            Integer status = null;
            try {
                aid = Integer.valueOf(cursor.getString(1));
                bid = Integer.valueOf(cursor.getString(2));
                status = Integer.valueOf(cursor.getString(3));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                Log.e("QueryActivity.java", "数据不能转化为数字,请检查！");
            }
            String returnTime = cursor.getString(4);
//            封装为对象
            AccountBookRelation accountBookRelation = new AccountBookRelation(aid, bid, status, returnTime);
//            添加入借阅记录
            accountBookRelationList.add(accountBookRelation);
        }
        if (accountBookRelationList.size() == 0 || accountBookRelationList == null) {
            toast = ToastUtil.toastHint(toast, LossBookActivity.this, "暂无借阅记录!");
            return;
        }
//        具有借阅记录
        /**
         * 遍历借阅记录，通过图书ID查询所属图书编号和名称并进行封装
         * 用图书归还日期判断当前借阅状态是归还逾期还是借阅中
         *  如果图书归还日期大于或等于今天，证明借阅中，如果小于当天，就证明归还已逾期
         */
//        Initialize List
        List<AccountBookRelationVO> accountBookRelationVOList = new ArrayList<>();
        for (AccountBookRelation accountBookRelation : accountBookRelationList) {
//            账号ID
            Integer aid = accountBookRelation.getAid();
//            图书ID
            Integer bid = accountBookRelation.getBid();
//            预计归还日期
            String returnTimeString = accountBookRelation.getReturnTimeString();
//            图书状态
            Integer status2 = accountBookRelation.getStatus();
//             通过图书ID查询图书信息，如果没有，则提示图书已不存在
            Book book = null;
            Cursor query = readableDatabase.query("BOOK", null, "ID = ?", new String[]{bid.toString()}, null, null, null);
            while (query.moveToNext()) {
                String bookNumber = query.getString(1);
                String bookName = query.getString(2);
//                通过构造函数进行封装
                book = new Book(bookNumber,bookName);
            }
//            判断该图书是否存在
            if (book == null) {
//                当前日期
                long time = new Date().getTime();
                long returnTime = DateUtil.stringDate(returnTimeString).getTime();
                String status = status2 == 1 ? "借阅中" : "已预约";
//                判断当前借阅书籍状态
                if (returnTime < time) {
                    status = "已逾期";
                }
                if (status2 == 2) {
                    status = "已归还";
                }
                AccountBookRelationVO accountBookRelationVO = new AccountBookRelationVO("0","*******",returnTimeString,status);
//                添加借阅记录集合
                accountBookRelationVOList.add(accountBookRelationVO);
                continue;
            }
            //                当前日期
            long time = DateUtil.stringDate(DateUtil.dateString(new Date(),"yyyy-MM-dd")).getTime();
            long returnTime = DateUtil.stringDate(returnTimeString).getTime();
            String status = status2 == 1 ? "借阅中" : "已预约";
//                判断当前借阅书籍状态
            if (returnTime < time) {
                status = "已逾期";
            }
            if (status2 == 2) {
                status = "已归还";
                continue;
            }

            //            判断借阅的书籍是否处于挂失阶段
            /**
             * 1、通过借阅记录额账号ID和图书ID查询是否具有挂失记录
             *  1.1、如果有，则状态修改为挂失状态
             *  1.2、没有则不变
             */
//            挂失状态：0 挂失中 1：已处理 2：已归还
            String lossStatus = "-1";
            Cursor loss_record = readableDatabase.query("LOSS_RECORD", null, "AID = ? AND BID = ?", new String[]{aid.toString(), bid.toString()}, null, null, null);
            while (loss_record.moveToNext()) {
                lossStatus = loss_record.getString(3);
            }
            int parseInt = Integer.parseInt(lossStatus);
//            挂失中
            if (parseInt == 0) status = "挂失中" ;
//            已处理不显示
            if (parseInt == 1) continue;
//            已归还不显示
            if (parseInt == 2) continue;
//            已预约不显示
            if (UserBorrowOrLossAdminActivity.BORROW_STATUS_0.equals(status)) continue;

            AccountBookRelationVO accountBookRelationVO = new AccountBookRelationVO(book.getBookNumber(),book.getBookName(),returnTimeString,status);
//                添加借阅记录集合
            accountBookRelationVOList.add(accountBookRelationVO);
        }

//        判断借阅记录是否为空
        if (accountBookRelationVOList.size() <= 0) {
            toast = ToastUtil.toastHint(toast, LossBookActivity.this, "暂时没有借阅记录，请预约后查看！");
            return;
        }
        //        存储获取到的数据
        List<Map<String, Object>> resultList = new ArrayList<>(50);
        for (AccountBookRelationVO accountBookRelationVO : accountBookRelationVOList) {
            Map<String, Object> map = new HashMap<>(8);
            //                对数据进行封装
            map.put("bookNumber", accountBookRelationVO.getBookNumber());
            map.put("bookName", accountBookRelationVO.getBookName());
            map.put("returnTime", accountBookRelationVO.getReturnTime());
            map.put("status", accountBookRelationVO.getStatus());
//                将封装的map集合存储到resulList集合中
            resultList.add(map);
        }
        //        进行封装，列表展示
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                LossBookActivity.this,
                resultList,
                R.layout.query_book,
                new String[]{
                        "bookNumber", "bookName",
                        "returnTime", "status"
                },
                new int[]{
                        R.id.query_current_book_number, R.id.query_current_book_name,
                        R.id.query_current_return_time, R.id.query_current_book_status
                }
        );
        queryLossListView.setAdapter(simpleAdapter);

    }


    /**
     * 给菜单项添加事件
     * @param item 菜单索引
     * @return
     */
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
//        获取上下文
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
//        得到listView中选择的条目绑定的Id
        String id = String.valueOf(info.id);
//        得到列表子节点的视图
        View targetView = info.targetView;
        //                获取单列 某一元素的控制权
        TextView bookNumberText = targetView.findViewById(R.id.query_current_book_number);
        TextView bookStatusText = targetView.findViewById(R.id.query_current_book_status);
//                获取元素内容
        String bookNumberToString = bookNumberText.getText().toString();
        String bookStatusToString = bookStatusText.getText().toString();
        Log.i("=====ListView列表绑定的ID==",id);
        Log.i("===== 对应的图书编号 ==",bookNumberToString);
        Log.i("===== 对应的图书状态 ==",bookStatusToString);
        switch (item.getItemId()) {
            case 0:
//                挂失事件的方法
                lossDiaLog(bookNumberToString,bookStatusToString);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    /**
     * 通过图书编号查询图书ID
     * @param bookStatusToString 图书状态
     * @param bookNumberToString 图书编号
     */
    private void lossDiaLog(final String bookNumberToString,final String bookStatusToString) {
        Log.i("LossBookActivity.java","挂失账号ID="+loginId);
        //        建立一个对话框
        //                添加一个弹出对话框
        AlertDialog alertDialog = new AlertDialog.Builder(LossBookActivity.this).create();
//                设置提示
        alertDialog.setMessage("确定要挂失该书籍吗？");
//                设置 确认按钮操作
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (bookStatusToString.equals(REPOSR_LOSS)) {
                    toast = ToastUtil.toastHint(toast,LossBookActivity.this,"该书籍正在挂失中,不能重复挂失哦,请尽快联系图书管理员！");
                    return;
                }
                // TODO: 2021/12/26 编写挂失操作（已完成）
//                通过图书编号查询图书ID
                String bookId = null;
                SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
                Cursor query = readableDatabase.query("BOOK", null, "BOOK_NUMBER = ? ", new String[]{bookNumberToString}, null, null, null);
                while (query.moveToNext()) {
                    bookId = query.getString(0);
                }
                if (bookId == null) {
                    toast = ToastUtil.toastHint(toast,LossBookActivity.this,"未查找相关书籍,请检查！");
                    return;
                }
                Log.i("LossBookActivity.java","挂失图书ID="+bookId);
//                新增挂失记录
                ContentValues contentValues = new ContentValues();
                contentValues.put("AID",loginId);
                contentValues.put("BID",bookId);
                contentValues.put("STATUS",0);
                contentValues.put("RECORD_TIME",DateUtil.dateString(new Date()));
                contentValues.put("CREATE_TIME",DateUtil.dateString(new Date()));
                contentValues.put("UPDATE_TIME",DateUtil.dateString(new Date()));
                long loss_record = readableDatabase.insert("LOSS_RECORD", null, contentValues);
                if (loss_record == -1) {
                    toast = ToastUtil.toastHint(toast,LossBookActivity.this,"挂失失败,请检查相关参数或操作！");
                    return;
                }
                toast = ToastUtil.toastHint(toast,LossBookActivity.this,"挂失成功,请尽快与图书管理员联系！");
                /**
                 * 查询借阅记录并进行刷新渲染
                 */
                findByLoginId(loginId,readableDatabase);
                return;
            }
        });
//        设置取消按钮操作
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                toast = ToastUtil.toastHint(toast,LossBookActivity.this,"本次操作已取消！");
                return;
            }
        });
//          显示对话框
        alertDialog.show();

    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}